package com.codeduck.kafka.demo.producer;

import com.codeduck.kafka.demo.message.MessageDemo01;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.kafka.support.SendResult;
import org.springframework.stereotype.Component;
import org.springframework.util.concurrent.ListenableFuture;

import javax.annotation.Resource;
import java.util.UUID;
import java.util.concurrent.ExecutionException;

/**
 * @author: <a href="mailto:codeduck@163.com">Codeduck</a>
 * @createDate: 2022-01-08
 */
@Component
public class ProducerService {

    @Resource
    private KafkaTemplate<Object, Object> kafkaTemplate;

    public SendResult syncSend(String id, String msg) throws ExecutionException, InterruptedException {
        // 创建 Demo01Message 消息
        MessageDemo01 message = new MessageDemo01(id, msg);
        // 同步发送消息
        return kafkaTemplate.send(MessageDemo01.TOPIC, message).get();
    }

    public ListenableFuture<SendResult<Object, Object>> asyncSend(String id, String msg){
        // 创建 Demo01Message 消息
        MessageDemo01 message = new MessageDemo01(id, msg);
        // 异步发送消息
        return kafkaTemplate.send(MessageDemo01.TOPIC, message);
    }
}
